<?php
/**
* @package mosRest
* @author Chad Auld and Ozgur Cem Sen (code@brilaps.com)
* @copyright Brilaps, LLC (http://brilaps.com)
* @link http://brilaps.com || http://wiki.brilaps.com
* @license http://www.opensource.org/licenses/gpl-license.php GNU/GPL v.2.
*/

/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

//unfortunately!
if (phpversion() < 5) {
    die( 'REST API requires PHP5 or later.' );
}

//Fix to allow compatibility with J!
if (!function_exists( 'T_' )) { function T_($string) {return $string;} }

//Bring in the base REST class
global $mosConfig_absolute_path;
$base_class = $mosConfig_absolute_path.'/components/com_rest/rest.class.php';
if (file_exists($base_class)) {
    require_once($base_class);
} else {
    die(T_('Before utilizing com_rest_content the com_rest base component must first be installed!'));
}

require_once($mainframe->getPath('class'));

switch( $task ) {
	case "dataRetrival":
	dataRetrival( $option );
	break;
	
	default:
	invalidRequest( $option );
	break;
}

/**
* Handles unknown task requests and responds with error wrapped in the requested encoding format
*/
function invalidRequest() {
    if (class_exists('mRestContent')) {
        $mRest = new mRestContent();
    } else {
        die(T_('Unable to load class: mRestContent'));
    }

    //Verify return format
	$returnFormat = trim(mosGetParam($_GET, 'output', ''));
	if ($mRest->validateReturnFormat($returnFormat)===false) {
	    $returnFormat='json'; //force json
	}
	$htmlReturnStatusCode = 400;
	$errorMessage = T_('Invalid request');
	$data = $mRest->restError($errorMessage, $returnFormat);
	$mRest->restResponse($htmlReturnStatusCode, $returnFormat, $data);
}

/**
* Performs the actual data retrival as request by the external REST interface
* See the wiki for parameter explanations - http://wiki.brilaps.com/wikka.php?wakka=MOStlyRESTcomContent
*/
function dataRetrival() {
	global $mosConfig_absolute_path;
	
	if (class_exists('mRestContent')) {
        $mRest = new mRestContent();
    } else {
        die(T_('Unable to load class: mRestContent'));
    }
    
	//Setup main variables
	$appId = trim(mosGetParam($_GET, 'appid', ''));	
	$contentId = intval(mosGetParam($_GET, 'contentid', 0));
	$sectionId = intval(mosGetParam($_GET, 'sectionid', -1));
	$categoryId = intval(mosGetParam($_GET, 'categoryid', -1));
	$contentLimit =  intval(mosGetParam($_GET, 'results', 10));
	$contentLimitOffset = intval(mosGetParam($_GET, 'start', 0));
	$contentCreateDateSort = trim(strtoupper(mosGetParam($_GET, 'create_date_sort', 'DESC')));
	$showCategories = trim(strtolower(mosGetParam($_GET, 'show_categories', 'n')));
	$validContentCreateDateSort = array('DESC', 'ASC');
	$callback = trim(mosGetParam($_GET, 'callback', ''));
	$apiQueryString = trim(mosGetParam($_GET, rawurldecode('query'), ''));
	$requestType = trim(mosGetParam($_GET, 'type', ''));
	$validRequestTypes = array('content', 'popular', 'rank', 'section');
	
	//Verify return format
	$returnFormat = trim(mosGetParam($_GET, 'output', ''));
	if ($mRest->validateReturnFormat($returnFormat)===false) {
	    $returnFormat='json'; //force json
	}
	
	//Validate we have a properly formed request
	$htmlReturnStatusCode = 200; //Start as OK
	$uri = $mRest->full_url();
	if ($mRest->verifyRestAPIKey($appId, $requestType, $uri)===false) {
		$htmlReturnStatusCode = 401;
		$errorMessage = T_('Invalid or blocked appid used in request!');
		$data = $mRest->restError($errorMessage, $returnFormat);
	} else if (!in_array($requestType, $validRequestTypes)) {
		$htmlReturnStatusCode = 400;
		$errorMessage = T_('Invaid request type!');
		$data = $mRest->restError($errorMessage, $returnFormat);
	} else if ($contentLimit<1 || $contentLimit>100) {
		$htmlReturnStatusCode = 400;
		$errorMessage = sprintf(T_('Invalid results parameter.  Must be between %s and %s.'), 1, 100);
		$data = $mRest->restError($errorMessage, $returnFormat);
	} else if (!in_array($contentCreateDateSort, $validContentCreateDateSort)) {
		$htmlReturnStatusCode = 400;
		$errorMessage = T_('Invalid create_date_sort parameter!');
		$data = $mRest->restError($errorMessage, $returnFormat);
	} else if ($returnFormat=='json' && !empty($callback) && $mRest->verifyJSONCallbackName($callback)===false) {
		$htmlReturnStatusCode = 400;
		$errorMessage = T_('Invalid JSON callback parameter!');
		$data = $mRest->restError($errorMessage, $returnFormat);
	} else if ($showCategories!='n' && $showCategories!='y') {
		$htmlReturnStatusCode = 400;
		$errorMessage = T_('Invalid show_categories parameter!');
		$data = $mRest->restError($errorMessage, $returnFormat);
	}
	
	//Continue with data retrival if the request parameters are valid
	if ($htmlReturnStatusCode==200) {
		switch ($requestType) {
			case 'content':
				if ($contentId>0) {
					$data = $mRest->getContentById($contentId, $returnFormat, $callback);
				} else if (!empty($apiQueryString)) {
					$data = $mRest->getContentBySearching($apiQueryString, $contentLimit, $contentLimitOffset, $returnFormat, $callback);
				} else {
					$data = $mRest->getContent($sectionId, $categoryId, $contentLimit, $contentLimitOffset, $contentCreateDateSort, $returnFormat, $callback);
				}
			break;

			case 'rank':
				$data = $mRest->getContentByRank($contentLimit, $contentLimitOffset, $returnFormat, $callback);
			break;
			
			case 'popular':
				$data = $mRest->getContentByPopularity($contentLimit, $contentLimitOffset, $returnFormat, $callback);
			break;
			
			case 'section':
				$data = $mRest->getSections($sectionId, $showCategories, $returnFormat, $callback);
			break;

			default:
			break;
		}
	}
	
	//Do final response
	$mRest->restResponse($htmlReturnStatusCode, $returnFormat, $data);
}

?>